public class ReverseKGroup {
    //  链表中的节点每k个一组翻转
    // https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode prev = null;
        ListNode cur = head;
        for (int i = 0; i < k; i++) {
            prev = cur;
            cur = cur.next;
            if (i != k-1 && cur == null) {
                return head;
            }
        }
        prev.next = null;
        ListNode nextHead = reverseKGroup(cur, k);
        ListNode newHead = reverseList(head);
        head.next = nextHead;
        return newHead;
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = prev;
            prev = cur;
            cur = curNext;
        }
        return prev;
    }

    public static void main1(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = null;
        System.out.println(new ReverseKGroup().reverseKGroup(node1, 2));
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;
        node2.next = null;
        System.out.println(new ReverseKGroup().reverseKGroup(node1, 2));
    }
}
